package com.qxy.practice.StringField;

import java.util.ArrayList;
import java.util.List;

public class StringTest {
    public static void main(java.lang.String[] args) {
        Solution3 solution3 = new Solution3();
        List<String> strings = solution3.restoreIpAddresses("0000");
    }
    
}

class Solution3 {
    private List<String> result = new ArrayList<>();
    private List<String> path = new ArrayList<>();
    public List<String> restoreIpAddresses(String s) {
        solutionHepler(s,0);
        return result;
    }
    private void solutionHepler(String string,int depth){
        if(string.length()==0 || string == null) return;
        if(depth == 3){
            //处理第四段子串
            if(isValidIp(string)){
                path.add(string);
                StringBuilder tmp =  new StringBuilder();
                for(int i =0 ; i<4;i++){
                    if(i==3){
                        tmp.append(path.get(i));
                    }else{
                        tmp.append(path.get(i)+".");
                    }
                }
                result.add(tmp.toString());
                path.remove(3);
                return;
            }else{
                return ;
            }
        }

        for(int i = 0 ; i<string.length();i++){
            List<String> tmp = splitHelper(string,i);
            String cur = tmp.get(0);
            String next = tmp.get(1);
            if(!isValidIp(cur)) continue;
            //前子串合法，保留
            path.add(cur);
            //切割后子串
            solutionHepler(next,depth+1);
            path.remove(path.size()-1);

        }

        return;
    }
    private List<String> splitHelper(String s, int index){
        List<String> result = new ArrayList<>();
        if(index+1 > s.length()) {
            result.add(s);
        }
        StringBuilder tmp1 = new StringBuilder();
        StringBuilder tmp2 = new StringBuilder();
        for(int i = 0 ; i<=index;i++){
            tmp1.append(s.charAt(i));
        }
        result.add(tmp1+"");
        for (int i = index+1; i <s.length(); i++) {
            tmp2.append(s.charAt(i));
        }
        result.add(tmp2+"");
        return result;
    }

    private boolean isValidIp(String s){
        int length = s.length();
        if(length==0 || length>3 || s.charAt(0)=='0'&&length!=1){
            return false;
        }
        Integer ip = Integer.valueOf(s);
        if(ip >=0 && ip < 256){
            return true;
        }else{
            return false;
        }
    }
}
